package handle

import (
	g "blog.wuzhispace.com/internal/global"
	"blog.wuzhispace.com/internal/model"
	"github.com/gin-gonic/gin"
)

type Article struct {
}

type SoftDeleteReq struct {
	Ids      []int `json:"ids"`
	IsDelete bool  `json:"is_delete"`
}

type AddOrEditArticleReq struct {
	ID      int    `json:"id"`
	Title   string `json:"title"`
	Desc    string `json:"desc" binding:"required"`
	Content string `json:"content" binding:"required"`
	Img     string `json:"img"`
	Type    int    `json:"type" binding:"required,min=1,max=3"`   // 类型: 1-原创 2-转载 3-翻译
	Status  int    `json:"status" binding:"required,min=1,max=3"` // 状态: 1-公开 2-私密 3-评论可见

	IsTop       bool   `json:"is_top"`
	OriginalUrl string `json:"original_url"`

	TagNames     []string `json:"tag_names"`
	CategoryName string   `json:"category_name"`
}

func (*Article) SaveOrUpdate(c *gin.Context) {
	var req AddOrEditArticleReq

	if err := c.ShouldBindJSON(&req); err != nil {
		ReturnError(c, g.ErrRequest, err)
		return
	}

	db := GetDB(c)
	auth, _ := CurrentUserAuth(c)

	if req.Img == "" {
		req.Img = model.GetConfig(db, g.CONFIG_ARTICLE_COVER) // 默认图片
	}

	if req.Type == 0 {
		req.Type = 1 // 默认原创
	}
	article := model.Article{
		Model:       model.Model{ID: req.ID},
		Title:       req.Title,
		Desc:        req.Desc,
		Content:     req.Content,
		Img:         req.Img,
		Type:        req.Type,
		Status:      req.Status,
		IsTop:       req.IsTop,
		OriginalUrl: req.OriginalUrl,
		UserId:      auth.UserInfoId,
	}

	err := model.SaveOrUpdateArticle(db, &article, req.CategoryName, req.TagNames)
	if err != nil {
		ReturnError(c, g.ErrDbOp, err)
		return
	}
	ReturnSuccess(c, article)
}
